iT邦幫忙

0

2024 IT鐵人賽 Day28 -localStorage

  • 分享至 

  • xImage
  •  

localStorage

語法:

儲存

localStorage.setItem("myCat", "Tom");

提取

var cat = localStorage.getItem("myCat");

提取

var cat = localStorage.getItem("myCat");

刪除

localStorage.removeItem("myCat");

全部資料刪除

localStorage.clear();
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Day28</title>
  </head>
  <body>
    <h2 class="textContent"></h2>

    <button class="SaveBtn">儲存</button>
    <button class="DeleteBtn">刪除</button>

    <script>
      const SaveBtn = document.querySelector(".SaveBtn");
      console.log(SaveBtn);
      const DeleteBtn = document.querySelector(".DeleteBtn");
      console.log(DeleteBtn);
      const textContent = document.querySelector(".textContent");
      console.log(textContent);

      SaveBtn.addEventListener("click", () => {   //  儲存
        console.log("有觸發");
        localStorage.setItem("text", "我被儲存");
        const cat = localStorage.getItem("text");
        textContent.innerHTML = cat;
      });

      DeleteBtn.addEventListener("click", () => {   //  移除顯示
        console.log("有觸發");
        localStorage.removeItem("text");

        textContent.innerHTML = "";
      });
    </script>
  </body>
</html>

https://ithelp.ithome.com.tw/upload/images/20241025/20169661uI7LXu2cUX.png


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言